import { loginAPI, getProfileAPI } from '@/api/user.js'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  // 数据状态 响应式
  state: {
    // 存token信息
    token: getToken() || '',
    userProfile: {}
  },
  // 同步修改
  mutations: {
    setToken(state, newToken) {
      // Vuex存储一份
      state.token = newToken
      // 存入本地cookie中
      setToken(newToken)
    },
    clearUserInfo(state) {
      state.token = ''
      state.userProfile = {}
      removeToken()
    },
    setUserProfile(status, userInfo) {
      status.userProfile = userInfo
    }
  },
  // 异步 发起接口请求并提交mutations
  actions: {
    async ActionLogin(context, { username, password }) {
      // 对登录接口发起请求，并获取到token
      const res = await loginAPI({ username, password })
      context.commit('setToken', res.data.token)
    },
    async getUserProfile(context) {
      const res = await getProfileAPI()
      context.commit('setUserProfile', res.data)
      return res.data.permissions
    }
  }
}
